<?php

/**
 * Util  Class with static functions for common use, such as string , date, time manipulation,etc..
 *
 * @package class
 */
class Util
{

    /**
     * Function getUrl used to get base url or get current page url.
     *
     * @param string $option Set to base or page
     *
     * @static
     * @access public
     *
     * @return string Full string contains url.
     */
    public static function getUrl($option = 'base')
    {

        $pageURL = 'http';

        if (isset($_SERVER['HTTPS']))
        {

            if ($_SERVER["HTTPS"] == "on")
            {

                $pageURL .= "s";
            }
        }

        $pageURL .= "://";

        if ($option == 'base')
        {

            if ($_SERVER["SERVER_PORT"] != "80")
            {

                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
            } else
            {

                $pageURL .= $_SERVER["SERVER_NAME"];
            }
        } else if ($option == 'page')
        {

            if ($_SERVER["SERVER_PORT"] != "80")
            {

                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
            } else
            {

                $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
            }
        } else
        {
            return FALSE;
        }

        return $pageURL;

    }

    public static function trimArray($array = array())
    {
        $returnArray = array();

        foreach ($array as $k => $v)
        {
            if (is_string($v))
            {
                $returnArray[trim($k)] = trim($v);
            } else if (is_array($v))
            {
                $returnArray[trim($k)] = self::trimArray($v);
            } else
            {
                $returnArray[trim($k)] = $v;
            }
        }

        return $returnArray;

    }

    public static function templateBaseUrl()
    {
        $templatePathArray = explode('/', trim(Config::get('app.template'), '/'));

        return Config::get('template.url') . '/' . $templatePathArray[count($templatePathArray) - 2];

    }

    public static function appSection($returnAsPath = true)
    {
        $configSections = Config::get('sections');

        foreach ($configSections as $section => $value)
        {

            if (strpos(self::getUrl('page'), self::getUrl() . '/' . $section) !== FALSE)
            {
                if ($returnAsPath)
                {
                    return '_' . ucfirst($section);
                } else
                {
                    return $section;
                }
            }
        }

        return '';

    }

    public static function geoByIp()
    {
        $geoData = @file_get_contents('http://api.hostip.info/get_json.php?ip=' . self::getRealIpAddr() . '&position=false');

        return json_decode($geoData, TRUE);

    }

    public static function moduleUrl()
    {
        return Config::get('app.module_url') . DS . Config::get('app.router')->getModule();

    }

    public static function getBrowser()
    {
        $versmatch = '(\);)?(\w*[\/|\s|-]\d+[\.\w]*(\s\[\w+\])?(\sMobile)?)?';
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $result = 'unknown';
        $checks = Array(
            'AOL' => 'AOL',
            'Avant Browser' => 'Avant Browser',
            'MSIE' => 'IE',
            'Chrome' => 'Chrome',
            'Navigator' => 'Netscape Navigator',
            'Iceweasel' => 'Iceweasel',
            'SeaMonkey' => 'SeaMonkey',
            'Firefox' => 'Firefox',
            'Safari' => 'Version Safari',
            'Nintendo Wii' => 'Opera',
            'Opera' => 'Opera',
            'Firebird' => 'Firebird',
            'Kazehakase' => 'Kazehakase',
            'Iceape' => 'Iceape',
            'Phoenix' => 'Phoenix',
            'Playstation 3' => 'Playstation 3',
            'PSP' => 'Playstation Portable',
            'Googlebot' => 'Googlebot',
            'msnbot' => 'msnbot-Products msnbot',
            'Yahoo! Slurp China' => 'Yahoo! Slurp China',
            'Yahoo! Slurp' => 'Yahoo! Slurp',
            'Ask Jeeves' => 'Ask Jeeves',
            'Cuil' => 'Twiceler',
            'Mozilla' => 'Mozilla',
            'BlackBerry' => 'BlackBerry'
        );

        foreach ($checks as $key => $check)
        {
            if (preg_match('/(' . $check . ')/', $agent) > 0)
            {
                preg_match('/' . $key . $versmatch . '/', $agent, $matches);
                $result = str_replace('-', ' ', str_replace(');', '', str_replace('/', ' ', $matches[0])));
                switch ($check)
                {
                    case 'Safari':
                        return str_replace($result, 'Version', 'Safari');
                        break;
                    case 'Navigator':
                        return str_replace($result, 'Navigator', 'Netscape');
                        break;
                    case 'msnbot':
                        return str_replace(str_replace($result, 'Products', ''), 'msnbot', 'Windows Live');
                        break;
                    case 'Cuil':
                        return str_replace($result, 'Twiceler', 'Cuil');
                        break;
                    case 'Nintendo Wii':
                        return str_replace($result, 'Opera', 'Nintendo Wii (Opera)');
                        break;
                    case 'BlackBerry':
                        return str_replace($result, 'BlackBerry', 'BlackBerry ');
                        break;
                }
                return $result;
            }
        }

    }

    public static function getOs()
    {
        $OSList = array
            (
            // Match user agent string with operating systems
            'Windows 3.11' => 'Win16',
            'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)',
            'Windows 98' => '(Windows 98)|(Win98)',
            'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
            'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
            'Windows Server 2003' => '(Windows NT 5.2)',
            'Windows Vista' => '(Windows NT 6.0)',
            'Windows 7' => '(Windows NT 7.0)',
            'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
            'Windows ME' => 'Windows ME',
            'Open BSD' => 'OpenBSD',
            'Sun OS' => 'SunOS',
            'Linux' => 'Linux',
            'Mac OS' => '(Mac_PowerPC)|(Macintosh)',
            'QNX' => 'QNX',
            'BeOS' => 'BeOS',
            'OS/2' => 'OS/2',
            'Search Bot' => '(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)'
        );

        // Loop through the array of user agents and matching operating systems
        foreach ($OSList as $CurrOS => $Match)
        {

            // Find a match
            if (stristr($_SERVER['HTTP_USER_AGENT'], $Match))
            {
                // We found the correct match
                break;
            }
        }

        // You are using Windows Vista
        return $CurrOS;

    }

    public static function message($message, $type = 'alerts')
    {
        $html = '<div class="alert alert-' . $type . '">
                        <button type="button" class="close" data-dismiss="alert">×</button>
                        ' . $message . '
                </div>';

        return $html;

    }

    public static function validateUrl()
    {
        return !preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', self::getUrl('page')) ? FALSE : TRUE;

    }

    public static function validateEmail($email)
    {
        return preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $email);

    }

    public static function validateUsername($username)
    {
        return preg_match('/^[a-z\d_]{5,20}$/i', $username);

    }

    public static function validateIP($IP)
    {
        return preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $IP);

    }

    public static function validateCreditCard($cc)
    {
        return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc);

    }

    public static function validateDomain($url)
    {
        return preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url);

    }

    public static function isHomepage()
    {
        return trim(self::getUrl('page'), '/') === trim(self::getUrl(), '/');

    }

    public static function checkArray($array)
    {
        return (is_array($array) && count($array) > 0);

    }

    public static function getRealIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP']))
        {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        //to check ip is pass from proxy
        {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else
        {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;

    }

}